package com.souche.sts.study;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @description: 只允许两个线程同时获取状态的锁
 *
 * @author: heqiang
 *
 * @create: 2019-09-25 17:44
 **/
public class TwinsLock implements Lock {

    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 7007896758627238368L;
        Sync(int count){
            if(count<=0){
                throw new IllegalArgumentException("count must large than zero");
            }
            setState(count);
        }

        public int tryAcquireShared(int reduceCount){
            for(;;){
                //current 值只有0，1，2，其中0表示已经有两个相等获得状态了
                int current = getState();
                //当newCount<0则表示已经有两个线程获得状态了，其他的要进入等待队列
                int newCount = current - reduceCount;
                if(newCount < 0 || compareAndSetState(current,newCount)){
                    return newCount;
                }
            }
        }
        public boolean tryReleaseShared(int returnCount){
            for(;;){
                int current = getState();
                //释放跟获取相反，是加一，然后一个个释放
                int newCount = current + returnCount;
                if(compareAndSetState(current,newCount)){
                    return true;
                }
            }
        }

    }
    //初始化允许2个线程获得
    private final Sync sync = new Sync(2);

    @Override
    public void lock() {
        sync.acquireShared(1);
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }



}
